<?php


namespace app\company\model;

use think\Db;
use think\Model;

// 检车项目管理

class Project extends Model
{
    public function getList()
    {
        $map['company_id'] = session('company.company_id');
        $list = Db::view('cd_vehicle', ['title' => 'vehicle_type'])
            ->view('cd_vehicle_inspection_company', 'id,inspection_id,license_type,goods_name,shop_price,sort,is_use', 'cd_vehicle.id=cd_vehicle_inspection_company.license_type')
            ->where($map)
            ->order('sort')
            ->select();
        return $list;
    }
    // 获取总数
    public function getCount($license_type)
    {
        // $map = ['is_delete' => 0];
        if ($license_type) {
            $map['license_type'] = ['like', "%{$license_type}%"];
        }
        $count = db('vehicle_inspection_company')
            ->field('company_id')
            ->where($map)
            ->count();
        return $count;
    }
    // 执行添加
    public function doAdd_project($data)
    {
        $inspection_id = $data['inspection_id'];
        $license_type = $data['license_type'];
        if(empty($inspection_id)){
            exception('检车项目，至少选择一项');
        }
        unset($data['inspection_id']);
        $data['company_id'] = session('company.company_id');
        //Array ( [license_type] => 3 [inspection_id] => 1 [shop_price] => 323.00 [sort] => 111 )
        $inspection = db('vehicle_inspection')
            ->where('license_type',$license_type)
            ->where('inspection_id',$inspection_id)
            ->where('is_delete',0)
            ->find();
        $data['inspection_id'] = $inspection['goods_id'];
        $data['goods_name'] = $inspection['goods_name'];
        if(empty($data['inspection_id'])){
            exception('管理员未设置该检车项目，请重新选择');
        }
        $one = db('vehicle_inspection_company')
            ->where('inspection_id',$data['inspection_id'])
            ->where('company_id', $data['company_id'])
            ->find();
        if($one){
            exception('检车项目已存在，请重新输入');
        }
        $result = db('vehicle_inspection_company')
            ->insert($data);
        if (!$result) {
            exception('添加失败');
        }
    }
    //执行删除
    public function doDelete($userId)
    {
        $result = db('vehicle_inspection_company')
            ->where('id', $userId)
            ->where('company_id', session('company.company_id'))
            ->delete();
        if (!$result) {
            exception('删除失败');
        }
    }
    // 执行修改
    public function doModify_project($data)
    {
        $id = $data['id'];
        unset($data['id'], $data['license_type'], $data['inspection_id']);
        $result = db('vehicle_inspection_company')
            ->where('id',$id)
            ->where('company_id',session('company.company_id'))
            ->update($data);
        if (!$result) {
            exception('修改失败');
        }
    }
}